from django.http import HttpResponse

from ...models.users import UsersGroup, Users

from ...utils.data_handle import usergroup_data_paging

import json


# 用户组的功能
def usergroup_list(request):
    '''
    用户组管理, 获取所有的用户组
    GET
    参数：groupname=nsd1512&page=1&page_size=15
    '''
    # 获取所有的参数
    get_params = request.GET.dict()
    
    # 判断用户是搜索单个组 还是获取所有的组
    if not get_params['groupname']:
        # 获取全部
        all_usergroup_obj =  UsersGroup.objects.all().order_by('id')
        usergroup_tree_json = usergroup_data_paging(all_usergroup_obj, get_params['page'], get_params['page_size'])
    else:
        # 搜索组
        one_usergroup_obj = UsersGroup.objects.filter(groupname__icontains=get_params['groupname']).order_by('id')
        usergroup_tree_json = usergroup_data_paging(one_usergroup_obj, get_params['page'], get_params['page_size'])
        
    res_mes = {
        "code": 0,
        "data": usergroup_tree_json
    }
    res_mes_json = json.dumps(res_mes, ensure_ascii=False)
    return HttpResponse(res_mes_json)


def usergroup_save(request):
    '''
    save
    post
    body = {'id': 1, 'groupname': 'Nsd1512', 'user_expired_time': '2024-09-30 17:50:37', 'chat_roles': ['gpt'], 'chat_models': [21, 22, 23, 24], 'status': True, 'chat_users': {'usersid': [3, 14, 13, 12, 2, 21]}}
    '''
    if request.method == 'POST':
        json_b = request.body
        json_str = json_b.decode('utf-8')
        json_obj = json.loads(json_str)

        # 先查询数据
        if "id" in json_obj:
            chatusersgroup_instance_list = UsersGroup.objects.filter(id=json_obj['id'])
            if chatusersgroup_instance_list:
                chatusersgroup_instance = chatusersgroup_instance_list[0]
            else:
                res_mes = {
                    "code": 1,
                    "message": "没有这个数据"
                }
                res_mes_json = json.dumps(res_mes, ensure_ascii=False)
                return HttpResponse(res_mes_json)
        else:
            chatusersgroup_instance_list = UsersGroup.objects.filter(groupname=json_obj['groupname'])
            if chatusersgroup_instance_list:
                res_mes = {
                    "code": 1,
                    "message": "用户组名已经被占用。已经有这个用户组！"
                }
                res_mes_json = json.dumps(res_mes, ensure_ascii=False)
                return HttpResponse(res_mes_json)
            else:
                chatusersgroup_instance = UsersGroup()

        # 保存数据
        for key, value in json_obj.items():
            if key == "chat_roles":
                if value:
                    chatusersgroup_instance.chat_roles_json = value
            elif key == "chat_models":
                if value:
                    chatusersgroup_instance.chat_models_json = value
            elif key == "user_expired_time":
                if value:
                    chatusersgroup_instance.user_expired_time = value
                else:
                    chatusersgroup_instance.user_expired_time = None
            elif key == "chat_users":
                # 遇到这个key 先什么都不做，后面再处理
                pass
            else:
                code_str = "chatusersgroup_instance.%s = '%s'" % (key, value)
                exec(code_str)

        # 保存数据到数据库
        try:
            chatusersgroup_instance.save()
        except Exception as e:
            res_mes = {
                "code": 1,
                "message": "保存数据失败！"
            }
            res_mes_json = json.dumps(res_mes, ensure_ascii=False)
            return HttpResponse(res_mes_json)
        
        # 绑定用户组中的用户
        # 先获取所有的用户实例
        try:
            all_user_obj = Users.objects.filter(id__in=json_obj['chat_users']['usersid'])

            chatusersgroup_instance.users.set(all_user_obj)
        except:
            res_mes = {
                "code": 1,
                "message": "绑定用户失败！用户组创建成功！"
            }
            res_mes_json = json.dumps(res_mes, ensure_ascii=False)
            return HttpResponse(res_mes_json)
        
        # 如果要是新增用户组的话 需要返回新增数据
        if "id" not in json_obj:
            add_usergroup_obj = UsersGroup.objects.filter(id=chatusersgroup_instance.id)
            usergroup_tree_json = usergroup_data_paging(add_usergroup_obj, 1, 10)

            res_mes = {
                "code": 0,
                "data": usergroup_tree_json['items'][0]
            }
        else:
            res_mes = {
                "code": 0
            }
        
        res_mes_json = json.dumps(res_mes, ensure_ascii=False)
        return HttpResponse(res_mes_json)
    

def usergroup_remove(request):
    re_id = request.GET.get('id')

    try:
        del_obj = UsersGroup.objects.get(id=re_id)
        del_obj.delete()

        res_mes = {
            "code": 0
        }
        res_mes_json = json.dumps(res_mes, ensure_ascii=False)
        return HttpResponse(res_mes_json)
    except Exception as e:
        res_mes = {
            "code": 1,
            "message": "删除失败!"
        }
        res_mes_json = json.dumps(res_mes, ensure_ascii=False)
        return HttpResponse(res_mes_json)

